package com.bbcare.followup.plat.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.*;
import com.bbcare.department.plat.entity.Doctor;
import com.bbcare.department.plat.service.impl.DepartmentBasicService;
import com.bbcare.department.plat.service.impl.DoctorManagerService;
import com.bbcare.exportExcel.plat.store.ibatis.IUploadExcelDAO;
import com.bbcare.extendContent.zdy.service.IZDYService;
import com.bbcare.followup.plat.dto.request.PatientPageReqDTO;
import com.bbcare.followup.plat.dto.request.PatientUpdateStatusReqDTO;
import com.bbcare.followup.plat.entity.*;
import com.bbcare.followup.plat.service.*;
import com.bbcare.followup.plat.store.ibatis.*;
import com.bbcare.treat.plat.service.IPatientArchService;
import com.bbcare.treat.plat.service.IPatientTreatService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

import static com.bbcare.comm.Constants.UPDATE_USER;

/**
 * @name: 患者信息控制类
 * @author: DemonLee
 * @createTime: 2017.4.11
 * @description: 患者建档、查询等与患者相关的操作
 * @modify:
 */
@RestController
@RequestMapping("/service/patient")
public class PatientController {
    private final Log logger = LogFactory.getLog(PatientController.class);

    @Autowired
    private IPatientDAO patientDao;

    @Autowired
    private IPatientService patientSerivce;

    @Autowired
    private IFollowQueueService followQueueService;

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IFollowQueueService followQueueSerivce;

    @Autowired
    private IPatientTreatService patientTreatService;

    @Autowired
    private IPatientArchService patientArchService;

    @Autowired
    public IConfCacheDAO confCacheDAO;

    @Autowired
    public IBaseChildService baseChildService;

    @Autowired
    public IUploadExcelDAO uploadExcelDAO;

    @Autowired
    private IPatientPhoneService patientPhoneService;

    @Autowired
    private DepartmentBasicService departmentBasicService;

    @Autowired
    private IZDYService izdyService;

    @Autowired
    private IPatientSwitchService patientSwitchService;

    @Autowired
    private FuClosecaseRecordService fuClosecaseRecordService;

    @Autowired
    private DoctorManagerService doctorManagerService;
    @Autowired
    private FuReferralRecordService fuReferralRecordService;
    @Autowired
    private FuReferralReturnRecordService fuReferralReturnRecordService;
    @Autowired
    private FuReferralRecordDao fuReferralRecordDao;

    @Autowired
    private IPatientTaskDAO patientTaskDao;

    @Autowired
    private IPatientTaskContentDAO patientTaskConDao;

    @Autowired
    private IPatientTaskContentDAO taskContentDAO;

    // 根据服务号码查询患者信息List
    @ResponseBody
    @RequestMapping("/patientQueryByPhoneNum")
    public ResultModel<HashMap<String, Object>> qryPatientByPhone(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in qryPatientByPhone----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String phoneNo = jsonData.getString("phoneNum");
        String hisNo = jsonData.getString("hisNo");
        String patientName = jsonData.getString("patientName");
        if (StringUtils.isBlank(phoneNo) && StringUtils.isBlank(hisNo) && StringUtils.isBlank(patientName)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参校验失败，服务号码、科研编号及患者姓名至少一个不能为空！"));
        }
        Integer schemeBusiType = jsonData.getInteger("schemeBusiType");
        if (null == schemeBusiType) {
            // 兼容老的随访系统，没传默认0
            schemeBusiType = Constants.SCHEME_BUSI_TYPE_0; // 0:科研随访方案；1:门诊诊疗方案；2:待扩展...
        }
        Map<String, Object> servParamMap = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(phoneNo)) {
            servParamMap.put("phoneNo", phoneNo);
        }
        if (StringUtils.isNotEmpty(hisNo)) {
            servParamMap.put("hisNo", hisNo);
        }
        if (StringUtils.isNotEmpty(patientName)) {
            servParamMap.put("userName", patientName + "%");
        }
        servParamMap.put("schemeBusiType", schemeBusiType);
        if (!StringUtils.isEmpty(jsonData.getString("followQueueId"))) {
            servParamMap.put("queueId", jsonData.getString("followQueueId"));
        }
        servParamMap.put("ptSchemeId", jsonData.getString("ptSchemeId"));

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        servParamMap.put("tenantId", tenantId);

        List<Object> list = patientSerivce.getPatientByPhoneNo(servParamMap);
        HashMap<String, Object> retMap = new HashMap<String, Object>();
        int total = 0;
        if (null != list) {
            total = list.size();
        }
        retMap.put("rows", list);
        retMap.put("total", total);

        return new ResultModel<HashMap<String, Object>>(retMap);
    }



    // 根据服务号码查询患者信息List
    @ResponseBody
    @RequestMapping("/getPatientById")
    public ResultModel<HashMap<String, Object>> getPatientById(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getPatientById----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        Map<String, Object> data = new HashMap<String, Object>();
        Iterator ite = jsonData.keySet().iterator();
        // 遍历jsonObject数据,添加到Map对象
        while (ite.hasNext()) {
            String key = ite.next().toString();
            String value = jsonData.get(key).toString();
            data.put(key, value);
        }
        Patient patient = patientSerivce.getPatient(data);

        return new ResultModel(patient);
    }

    // 患者信息List查询
    @ResponseBody
    @RequestMapping("/patientListQuery")
    public ResultModel<HashMap<String, Object>> getPatientList(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getPatientList0----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        String phoneNo = jsonData.getString("phoneNum");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);
        paramMap.put("phoneNo", phoneNo);
        paramMap.put("tenantId", tenantId);

        List<Patient> list = patientSerivce.getPatientList(paramMap);
        HashMap<String, Object> retMap = new HashMap<String, Object>();
        int total = 0;
        if (null != list) {
            total = list.size();
        }
        retMap.put("rows", list);
        retMap.put("total", total);

        return new ResultModel<HashMap<String, Object>>(retMap);
    }

    // 患者添加
    @ResponseBody
    @RequestMapping("/patientAdd")
    public ResultModel<Map<String, Object>> savePatientInfo(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in savePatientInfo----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String currTime = jsonData.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

        // 参数校验后续补充
        String queueId = jsonData.getString("followQueueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> chkMapIn = new HashMap<String, Object>();
        boolean isVerify = true;
        map.put("id", queueId);
        chkMapIn.put("queueId", queueId);
        FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
        if (null == queue) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
        }
        String queueUserType = queue.getQueueUsertype();

        Map<String, Object> servParamMap = jsonData;

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String refTenantId = (String) sessionMap.get("refTenantId");

        String deptId = (String) sessionMap.get("deptId");
        if (StringUtils.isBlank(deptId)) {
            deptId = queue.getDeptId();
        }
        String opCode = jsonData.getString("opCode");
        String opType = jsonData.getString("opType");
        if (StringUtils.isBlank(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作编码为空！"));
        }
        if (StringUtils.isBlank(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作类型为空！"));
        }
        if (StringUtils.isBlank(jsonData.getString("opNote"))) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作备注为空！"));
        }
        String userType = jsonData.getString("userType");
        if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            // 孕产妇（母亲），暂时写死，回头完善
            userType = "2";
            servParamMap.put("userType", userType);
        } else if (StringUtils.isBlank(userType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者类型为空！"));
        }

        // 入参中没有，从问卷答案中获取
        Map<String, Object> quesMap = (JSONObject) jsonData.getJSONObject("questiones");

        String phoneNum = jsonData.getString("phoneNum");
        if (StringUtils.isBlank(phoneNum)) {
            if (null != quesMap && 0 != quesMap.size()) {
                phoneNum = (String) quesMap.get(Constants.QUESTION_ID_FOR_PHONENO);
            }
        }
        if (StringUtils.isBlank(phoneNum)) {
            phoneNum = "";
            chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PHONENO);
            isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
            if (isVerify) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码不能为空！"));
            }
        }
        phoneNum = phoneNum.trim();

        String patientName = jsonData.getString("patientName");
        if (StringUtils.isBlank(patientName)) {
            if (null != quesMap && 0 != quesMap.size()) {
                patientName = (String) quesMap.get(Constants.QUESTION_ID_FOR_PATIENTNAME);
            }
        }
        if (StringUtils.isBlank(patientName)) {
            patientName = "";
            chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PATIENTNAME);
            isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
            if (isVerify) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者姓名不能为空！"));
            }
        }
        patientName = patientName.trim();

        String gender = jsonData.getString("gender");
        if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            // 孕产妇（母亲）
            gender = Constants.GENDER_FOR_FEMALE;
        } else if (StringUtils.isBlank(gender)) {
            if (null != quesMap && 0 != quesMap.size()) {
                gender = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
            }
        }
        if (StringUtils.isBlank(gender)) {
            gender = "";
            chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_GENDER);
            isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
            if (isVerify) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "性别不能为空！"));
            }
        }
        gender = gender.trim();
        // 转换性别
        if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_FEMALE;
        } else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        }

        String birthday = jsonData.getString("birthday");
        if (StringUtils.isBlank(birthday)) {
            if (null != quesMap && 0 != quesMap.size()) {
                birthday = (String) quesMap.get(Constants.QUESTION_ID_FOR_BIRTHDAY);
            }
        }
        if (StringUtils.isBlank(birthday) && !Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            birthday = null;
            chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_BIRTHDAY);
            isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
            if (isVerify) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "出生日期不能为空！"));
            }
        }

        // 预产期
        String expectedDay = jsonData.getString("expectedDay");
        if (StringUtils.isBlank(expectedDay)) {
            if (null != quesMap && 0 != quesMap.size()) {
                expectedDay = (String) quesMap.get(Constants.QUESTION_ID_FOR_EXPECTEDDAY);
            }
        }
        if (StringUtils.isEmpty(expectedDay)) {
            expectedDay = null;
        }

        // 出生胎龄(孕周)
        int pregnancyDay = 0;
        // 直接从入参中获取
        if (null != jsonData.getInteger("pregnancyWeek")) {
            pregnancyDay = jsonData.getIntValue("pregnancyWeek");
        }
        // 再考虑从问卷中获取，问卷存储格式：[39,5]
        if (pregnancyDay <= 0 && !MapUtils.isEmpty(quesMap)) {
            String preStr = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY);
            if (!StringUtils.isBlank(preStr)) {
                String preArr[] = preStr.split(Constants.COMMA_SPLIT_STR);
                if (null != preArr && 2 == preArr.length) {
                    String preWeekStr = preArr[0].substring(1);
                    String preDayStr = preArr[1].substring(0, preArr[1].length() - 1);
                    int preWeek = Integer.parseInt(preWeekStr);
                    int preDay = Integer.parseInt(preDayStr);
                    pregnancyDay = preWeek * Constants.PREGNANCY_CALC_UNIT_WEEK + preDay;
                }
            }
        }
        // 最后根据根据生日和预产期计算
        if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            // 孕产妇（母亲）
            // 初检孕周
            String firstChkPregWeek = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCY_FIRST_WEEK);
            if (StringUtils.isBlank(firstChkPregWeek)) {
                // 不在这里校验，在实例化随访任务时校验
            } else {
                servParamMap.put("firstChkPregWeek", Integer.parseInt(firstChkPregWeek));
            }
            // 末次月经日期
            String lastMenstruationDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_LAST_MENSTRUATION_DATE);
            if (StringUtils.isBlank(lastMenstruationDate)) {
                // 不在这里校验，在实例化随访任务时校验
            } else {
                servParamMap.put("lastMenstruationDate", lastMenstruationDate);
            }
            // 分娩日期
            servParamMap.put("deliveryDate", quesMap.get(Constants.QUESTION_ID_FOR_LAST_DELIVERY_DATE));
        } else if (pregnancyDay <= 0 && !StringUtils.isBlank(expectedDay)) {
            pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
        }

        // 孕周未填，默认280
        if (pregnancyDay <= 0) {
            pregnancyDay = Constants.PATIENT_NORMAL_PREGNANT_DAY;
        }
        // 预产期未填，默认与出生日期一致
        if (StringUtils.isBlank(expectedDay)) {
            expectedDay = birthday;
        }

        if (pregnancyDay > 300) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "尊敬的用户，您填写的出生日期或者预产期不正确，请检查！");
        }

        // 来源渠道
        String sourceType = jsonData.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            // 默认web端门诊渠道
            sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        }

        //患者在医院编号 2021年2月25日添加
        String hospitalNo = jsonData.getString("hospitalNo");
        if (StringUtils.isBlank(hospitalNo)) {
            if (null != quesMap && 0 != quesMap.size()) {
                hospitalNo = (String) quesMap.get("hospitalNo");
            }
        }
        //档案编号 2022年09月16日添加

        String fileNo = jsonData.getString("fileNo");
        if (StringUtils.isBlank(fileNo)) {
            if (null != quesMap && 0 != quesMap.size()) {
                fileNo = (String) quesMap.get(Constants.QUESTION_ID_FOR_FILE_NO);
            }
        }

        String idCard = jsonData.getString("idCard");
        if (StringUtils.isBlank(idCard)) {
            if (null != quesMap && 0 != quesMap.size()) {
                idCard = (String) quesMap.get(Constants.QUESTION_ID_FOR_IDCARD);
            }
        }

        Patient pt = new Patient();
        if(StringUtils.isNotEmpty(refTenantId)){
            pt.setUserStatus(Constants.PTUSER_PATIENT_USER_STATUS_WAIT_INITIATE_REFERRAL);
        }
        pt.setIdCard(idCard);
        pt.setPregnancyDay(pregnancyDay);
        pt.setUserName(patientName);
        pt.setPhoneNo(phoneNum);
        pt.setFirstName(patientName.substring(0, 1));
        pt.setCreateTime(currTime);
        pt.setUpdateTime(currTime);
        pt.setCreateAuthor(author);
        pt.setBirthday(birthday);
        pt.setExpectedDay(expectedDay);
        pt.setGender(gender);
        pt.setUserType(userType);
        pt.setSourceType(sourceType);
        pt.setHospitalNo(hospitalNo);
        pt.setFileNo(fileNo);

        servParamMap.put("patient", pt);
        servParamMap.put("authorName", authorName);
        servParamMap.put("deptId", deptId);
        servParamMap.put("queueId", queueId);
        servParamMap.put("updateTime", currTime);
        servParamMap.put("authorId", author);
        servParamMap.put("updateAccept", updateAccept);
        servParamMap.put("tenantId", tenantId);
        servParamMap.put("opCode", opCode);
        servParamMap.put("opNote", jsonData.getString("opNote"));
        servParamMap.put("opType", opType);
        servParamMap.put("contentData", jsonData.getJSONObject("questiones"));
        Map<String, Object> userMap = patientSerivce.registerPatient(servParamMap);

        String userId = (String) userMap.get("patientId");
        patientSwitchService.updatePreCheckStatus(userId,tenantId,queueId,deptId);
        if (userId != null && userId != "") {
            String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();
            // 新增患者成功后推送患者id到小程序
            // type=13 新增患者
            int type = 13;
            // system=1 2.0系统
            int system = 1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type",type);
            jsonObject.put("platType",platType);
            jsonObject.put("userId",userId);
            jsonObject.put("system",system);
            jsonObject.put("tenantId",tenantId);
            jsonObject.put("deptId",deptId);
            String sendMsg = jsonObject.toJSONString();
            if (StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl")))  {
                //如果config.properties中有redirectUrl配置项，才会发送请求。没有配置项，就不发送了。
                HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl") ,sendMsg);
            }
        }
        return new ResultModel<Map<String, Object>>(userMap);
    }


    //批量添加患者
    @ResponseBody
    @RequestMapping("/batchPatientAdd")
    public ResultModel<Map<String, Object>> batchAddPatientInfo(HttpServletRequest request)
            throws Exception {

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        List Patientlist = new ArrayList();
        String queueId = null;
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (!file.isEmpty()) {
                    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
                    if (!"csv".equals(suffix) && !"xlsx".equals(suffix) && !"xls".equals(suffix)) {
                        throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_FILE_TYPE_INCORRECT, "文件格式不对");
                    }

                    Workbook workbook = null;
                    Sheet sheet = null;
                    if (ToolUtils.isExcel2003(file.getOriginalFilename())) {
                        workbook = new HSSFWorkbook(file.getInputStream());
                    } else if (ToolUtils.isExcel2007(file.getOriginalFilename())) {
                        workbook = new XSSFWorkbook(file.getInputStream());
                    }

                    //第一行为标题
                    ArrayList Objlists = new ArrayList();
                    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                        sheet = workbook.getSheetAt(i);
                        //获取每行  从第二行开始
                        for (int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
                            ArrayList Sheetlist = new ArrayList();
                            Row row = sheet.getRow(j);
                            for (int k = 0; k < row.getLastCellNum(); k++) {
                                Cell cell = row.getCell(k, Row.RETURN_BLANK_AS_NULL);
                                if (cell != null) {
                                    //获取值并自己格式化
                                    switch (cell.getCellType()) {
                                        case Cell.CELL_TYPE_STRING:// 字符串型
                                            Sheetlist.add(cell.getRichStringCellValue().getString());
                                            break;
                                        case Cell.CELL_TYPE_NUMERIC:// 数值型
                                            if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) { // 如果是date类型则 ，获取该cell的date值
                                                Date date = cell.getDateCellValue();
                                                Sheetlist.add(DateUtil.getDateA(date));
                                            } else {// 纯数字
                                                cell.setCellType(Cell.CELL_TYPE_STRING);
                                                Sheetlist.add(cell.getStringCellValue());
                                            }
                                            break;
                                        case Cell.CELL_TYPE_BOOLEAN:// 布尔
                                            Sheetlist.add(cell.getBooleanCellValue());
                                            break;
                                        case Cell.CELL_TYPE_FORMULA:// 公式型
                                            Sheetlist.add(cell.getCellFormula());
                                            break;
                                        case Cell.CELL_TYPE_BLANK:// 空值
                                            Sheetlist.add(null);
                                            break;
                                        case Cell.CELL_TYPE_ERROR: // 故障
                                            Sheetlist.add(null);
                                            break;
                                        default:
                                            Sheetlist.add(null);
                                    }
                                } else {
                                    continue;
                                }
                            }
                            Objlists.add(Sheetlist);
                        }
                    }
                    // 获取指定模板的第一列值作为key

                    List Keylist = (List) Objlists.get(0);
                    // 指定模板的第一列的第一个值为队列id
                    queueId = (String) Keylist.get(0);
                    for (int i = 1; i < Objlists.size(); i++) {
                        List Objlist = (List) Objlists.get(i);
                        if (!Objlist.isEmpty() && Objlist != null) {
                            Map listMap = new HashMap();
                            for (int j = 0; j < Objlist.size(); j++) {
                                String key = (String) Keylist.get(j + 1);
                                listMap.put(key, Objlist.get(j));
                            }
                            Patientlist.add(listMap);
                        } else {
                            continue;
                        }
                    }
                }
            }
        }

        if (CollectionUtils.isEmpty(Patientlist)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_FILE_CONTENT_IS_EMPTY, "excel内容为空");
        }

        int number = 0;
        int failnumber = 0;

        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> chkMapIn = new HashMap<String, Object>();
        boolean isVerify = true;
        map.put("id", queueId);
        chkMapIn.put("queueId", queueId);
        FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
        if (null == queue) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
        }

        String queueUserType = queue.getQueueUsertype();

        Map<String, Object> servParamMap = new HashMap<String, Object>();

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");
        if (StringUtils.isBlank(deptId)) {
            deptId = queue.getDeptId();
        }
        // 操作编码默认：1000（患者建档）
        String opCode = "1000";
        // 操作备注
        String opNote = "批量建档";
        // 操作类型默认：2（门诊）
        String opType = "2";
        // 患者来源渠道默认：2（门诊建档）
        String sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        // 创建时间
        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());

        String userType = null;
        if (Constants.QUEUE_USER_TYPE_BABY.equals(queueUserType)) {
            // 宝宝
            userType = "1";
            servParamMap.put("userType", userType);
        } else if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
            // 孕产妇
            userType = "2";
            servParamMap.put("userType", userType);
        } else if (Constants.QUEUE_USER_TYPE_OTHER.equals(queueUserType)) {
            // 其他
            userType = "3";
            servParamMap.put("userType", userType);
        }

        List failList = new ArrayList();
        List successList = new ArrayList();
        Map<String, Object> quesMap = new HashMap<>();
        Map<String, Object> userMap = new HashMap<>();
        for (int i = 0; i < Patientlist.size(); i++) {
            quesMap.clear();
            quesMap = (Map<String, Object>) Patientlist.get(i);
            String phoneNum = null;
            String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
            if (StringUtils.isBlank(phoneNum)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    phoneNum = (String) quesMap.get(Constants.QUESTION_ID_FOR_PHONENO);
                }
            }
            if (StringUtils.isBlank(phoneNum)) {
                phoneNum = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PHONENO);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码不能为空！"));
                }
            }
            phoneNum = phoneNum.trim();

            String patientName = null;
            if (StringUtils.isBlank(patientName)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    patientName = (String) quesMap.get(Constants.QUESTION_ID_FOR_PATIENTNAME);
                }
            }
            if (StringUtils.isBlank(patientName)) {
                patientName = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_PATIENTNAME);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者姓名不能为空！"));
                }
            }
            patientName = patientName.trim();
            String gender = null;
            if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                // 孕产妇（母亲）
                gender = Constants.GENDER_FOR_FEMALE;
            } else if (StringUtils.isBlank(gender)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    gender = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
                }
            }
            if (StringUtils.isBlank(gender)) {
                gender = "";
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_GENDER);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "性别不能为空！"));
                }
            }
            gender = gender.trim();
            // 转换性别
            if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
                gender = Constants.GENDER_FOR_MALE;
            } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
                gender = Constants.GENDER_FOR_FEMALE;
            } else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
                gender = Constants.GENDER_FOR_MALE;
            }
            String birthday = null;
            if (StringUtils.isBlank(birthday)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    birthday = (String) quesMap.get(Constants.QUESTION_ID_FOR_BIRTHDAY);
                    // Excel获取年龄格式为yyyy-MM-dd HH:mm:ss处理成yyyy-MM-dd格式，方便后续时间节点计算
                    String[] birthdays = birthday.split(" ");
                    birthday = birthdays[0];
                }
            }
            if (StringUtils.isBlank(birthday) && !Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                birthday = null;
                chkMapIn.put("quesId", Constants.QUESTION_ID_FOR_BIRTHDAY);
                isVerify = patientArchService.isVerifyArchiveParam(chkMapIn);
                if (isVerify) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "出生日期不能为空！"));
                }
            }

            // 预产期
            String expectedDay = null;
            if (StringUtils.isBlank(expectedDay)) {
                if (null != quesMap && 0 != quesMap.size()) {
                    expectedDay = (String) quesMap.get(Constants.QUESTION_ID_FOR_EXPECTEDDAY);
                    // Excel获取年龄格式为yyyy-MM-dd HH:mm:ss处理成yyyy-MM-dd格式，方便后续时间节点计算
                    if (expectedDay != null && expectedDay != "") {
                        String[] expectedDays = expectedDay.split(" ");
                        expectedDay = expectedDays[0];
                    } else {
                        expectedDay = null;
                    }
                }
            }
            if (StringUtils.isEmpty(expectedDay)) {
                expectedDay = null;
            }

            // 出生胎龄(孕周)
            int pregnancyDay = 0;
            // 再考虑从问卷中获取，问卷存储格式：[39,5]
            if (pregnancyDay <= 0 && !MapUtils.isEmpty(quesMap)) {
                String preStr = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY);
                if (!StringUtils.isBlank(preStr)) {
                    String preArr[] = preStr.split(Constants.COMMA_SPLIT_STR);
                    if (null != preArr && 2 == preArr.length) {
                        String preWeekStr = preArr[0].substring(1);
                        String preDayStr = preArr[1].substring(0, preArr[1].length() - 1);
                        int preWeek = Integer.parseInt(preWeekStr);
                        int preDay = Integer.parseInt(preDayStr);
                        pregnancyDay = preWeek * Constants.PREGNANCY_CALC_UNIT_WEEK + preDay;
                    }
                }
            }
            // 最后根据根据生日和预产期计算
            if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                // 孕产妇（母亲）
                // 初检孕周
                String firstChkPregWeek = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCY_FIRST_WEEK);
                if (StringUtils.isBlank(firstChkPregWeek)) {
                    // 不在这里校验，在实例化随访任务时校验
                } else {
                    servParamMap.put("firstChkPregWeek", Integer.parseInt(firstChkPregWeek));
                }
                // 末次月经日期
                String lastMenstruationDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_LAST_MENSTRUATION_DATE);
                if (StringUtils.isBlank(lastMenstruationDate)) {
                    // 不在这里校验，在实例化随访任务时校验
                } else {
                    servParamMap.put("lastMenstruationDate", lastMenstruationDate);
                }
                // 分娩日期
                servParamMap.put("deliveryDate", quesMap.get(Constants.QUESTION_ID_FOR_LAST_DELIVERY_DATE));
            } else if (pregnancyDay <= 0 && !StringUtils.isBlank(expectedDay)) {
                pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
            }

            // 孕周未填，默认280
            if (pregnancyDay <= 0) {
                pregnancyDay = Constants.PATIENT_NORMAL_PREGNANT_DAY;
            }
            // 预产期未填，默认与出生日期一致
            if (StringUtils.isBlank(expectedDay)) {
                expectedDay = birthday;
            }

            if (pregnancyDay > 300) {
                throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        "尊敬的用户，您填写的出生日期或者预产期不正确，请检查！");
            }

            // 防止重复新建患者
            Map<String, Object> qryPtMap = new HashMap<String, Object>();
            qryPtMap.put("phoneNo", phoneNum);
            qryPtMap.put("userName", patientName);
            qryPtMap.put("tenantId", tenantId);
            // 不同类型用户
            qryPtMap.put("userType", servParamMap.get("userType"));
            List<Patient> ptList = patientDao.selectByPhoneNo(qryPtMap);
            List<PatientQueueScheme> pqsList = new ArrayList<PatientQueueScheme>();
            if (!org.springframework.util.CollectionUtils.isEmpty(ptList)) {
                // 校验患者是否已经加入过该队列
                HashMap<String, Object> qryPqsMap = new HashMap<String, Object>();
                qryPqsMap.put("userId", ptList.get(0).getId());
                qryPqsMap.put("queueId", queueId);

                List<String> statulist = new ArrayList<String>();

                statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);

                qryPqsMap.put("status", statulist);

                pqsList = patientQueueSchemeDao.selectByUserId(qryPqsMap);
            }

            if (org.springframework.util.CollectionUtils.isEmpty(pqsList)) {
                Patient pt = new Patient();
                pt.setPregnancyDay(pregnancyDay);
                pt.setUserName(patientName);
                pt.setPhoneNo(phoneNum);
                pt.setFirstName(patientName.substring(0, 1));
                pt.setCreateTime(currTime);
                pt.setUpdateTime(currTime);
                pt.setCreateAuthor(author);
                pt.setBirthday(birthday);
                pt.setExpectedDay(expectedDay);
                pt.setGender(gender);
                pt.setUserType(userType);
                pt.setSourceType(sourceType);
                try {
                    servParamMap.put("patient", pt);
                    servParamMap.put("authorName", authorName);
                    servParamMap.put("deptId", deptId);
                    servParamMap.put("queueId", queueId);
                    servParamMap.put("updateTime", currTime);
                    servParamMap.put("authorId", author);
                    servParamMap.put("updateAccept", updateAccept);
                    servParamMap.put("tenantId", tenantId);
                    servParamMap.put("opCode", opCode);
                    servParamMap.put("opNote", opNote);
                    servParamMap.put("opType", opType);
                    servParamMap.put("contentData", quesMap);
                    userMap = patientSerivce.registerPatient(servParamMap);

                    String userId = (String) userMap.get("patientId");

                    if (userId != null && userId != "") {


                        // type=13 新增患者
                        int type = 13;
                        // system=1 2.0系统
                        int system = 1;
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("type",type);
                        jsonObject.put("userId",userId);
                        jsonObject.put("system",system);
                        jsonObject.put("tenantId",tenantId);
                        jsonObject.put("deptId",deptId);
                        String sendMsg = jsonObject.toJSONString();
                        HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl") ,sendMsg);
                    }
                } catch (Exception e) {

                    failnumber++;

                    Map failMap = new HashMap();
                    failMap.put("serNumber", failnumber);
                    failMap.put("failPatientName", patientName);
                    failMap.put("failPatientPhone", phoneNum);
                    failMap.put("failPatientGender", gender);
                    failMap.put("createTime", DateUtil.getSysDateA());
                    failMap.put("successState", 0);

                    failList.add(failMap);

                    continue;
                }

                number++;

                Map successMap = new HashMap();
                successMap.put("successNumber", number);
                successMap.put("failPatientName", patientName);
                successMap.put("failPatientPhone", phoneNum);
                successMap.put("failPatientGender", gender);
                successMap.put("createTime", DateUtil.getSysDateA());
                successMap.put("successState", 1);

                successList.add(successMap);
            } else {

                failnumber++;

                Map failMap = new HashMap();
                failMap.put("serNumber", failnumber);
                failMap.put("failPatientName", patientName);
                failMap.put("failPatientPhone", phoneNum);
                failMap.put("failPatientGender", gender);
                failMap.put("createTime", DateUtil.getSysDateA());
                failMap.put("successState", 0);

                failList.add(failMap);

                continue;

            }

        }

        Map stateMap = new HashMap();
        // 成功数量
        stateMap.put("successNumber", number);
        // 失败数量
        stateMap.put("failNumber", failnumber);
        // 失败用户信息
        stateMap.put("failPatientList", failList);
        // 成功用户信息
        stateMap.put("successList", successList);

        logger.debug("out batchPatientAdd----arg==");
        return new ResultModel<Map<String, Object>>(stateMap);
    }


    // 患者信息List查询
    @ResponseBody
    @RequestMapping("/patientQueueListQuery")
    public ResultModel<HashMap<String, Object>> qryPatientQueueSchemeList(@RequestBody String arg,
                                                                          HttpServletRequest request) throws Exception {
        logger.warn("in qryPatientQueueSchemeList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        Integer ageTo = jsonData.getInteger("ageTo");
        Integer ageFrom = jsonData.getInteger("ageFrom");

        Calendar to = Calendar.getInstance();
        if (ageTo != null) {
            to.add(Calendar.MONTH, -ageTo);
            paramMap.put("ageTo", DateUtil.getDate_8(to.getTime()));
        }

        Calendar from = Calendar.getInstance();
        if (ageFrom != null) {
            from.add(Calendar.MONTH, -ageFrom);
            // from.set(Calendar.DAY_OF_MONTH,
            // from.getActualMaximum(Calendar.DAY_OF_MONTH));
            paramMap.put("ageFrom", DateUtil.getDate_8(from.getTime()));
        }

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            // 默认查询当日待随访的患者
            flag = "0";
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        String hisNo = jsonData.getString("hisNo");// 科研编号
        String fuzzyVar = jsonData.getString("fuzzyVar");// 姓名或科研编号
        String scaleAssessStatus = jsonData.getString("scaleAssessStatus");
        if (StringUtils.isNotEmpty(scaleAssessStatus)){
            paramMap.put("scaleAssessStatus",scaleAssessStatus);
        }

        //Edit by jiangq on 2023年08月18日 通过关联队列的用户id相同，查询用户属于多个队列的信息
        String patientId = jsonData.getString("patientId");// 用户id

        if (!StringUtils.isEmpty(fuzzyVar)) {
            paramMap.put("fuzzyVar", fuzzyVar.replace(" ", "") + "%");
        }
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (!StringUtils.isEmpty(patientId)) {
            paramMap.put("patientId", patientId);
        }

        if (!StringUtils.isEmpty(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (!StringUtils.isEmpty(userName)) {
            paramMap.put("userName", userName);
            //增加通过拼音查询用户
            paramMap.put("namePinyin", userName.toLowerCase() + "%");
            //名字简拼
            paramMap.put("nameInitial", userName.toLowerCase() + "%");
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("sourceType", jsonData.getString("opType"));
        paramMap.put("premature", jsonData.getString("premature"));
        paramMap.put("qryEndTime", jsonData.getString("qryEndTime"));
        paramMap.put("qryStartTime", jsonData.getString("qryStartTime"));
        if (!StringUtils.isEmpty(hisNo)) {
            paramMap.put("hisNo", hisNo);
        }
        // 可以查询队列中正常状态患者，也可查询扫码建档待审核状态的患者
        String confirmFlag = jsonData.getString("confirmFlag");
        if (StringUtils.isNotEmpty(confirmFlag)) {
            paramMap.put("confirmFlag", confirmFlag);
        }
        paramMap.put("systemType", jsonData.getString("systemType"));// 系统类型，00随访，01诊疗
        paramMap.put("taskAuditStatus", jsonData.getString("taskAuditStatus"));

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        // 特殊处理一妇婴倍力多项目
        paramMap.put("showFlag", jsonData.getString("showFlag"));
        long time = System.currentTimeMillis();
        HashMap<String, Object> retMap = patientSerivce.qryPatientQueueSchemeList(paramMap);
        long time2 = System.currentTimeMillis();
        System.out.println("ceshi1789  : " + (time2 - time));
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }

        return new ResultModel<HashMap<String, Object>>(retMap);
    }

    // 患者信息List查询
    @ResponseBody
    @RequestMapping("/patientListForDatatableQuery")
    public Map<String, Object> qryPatientListForDatatable(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in qryPatientQueueSchemeList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        // String authorId = "18812345678";
        // String tenantId = "aaa";

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            // 默认查询当日待随访的患者
            flag = "0";
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        String status = jsonData.getString("status");
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (null != status && !"".equals(status)) {
            paramMap.put("status", status);
        }
        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("userName", userName);
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("sourceType", jsonData.getString("opType"));
        // paramMap.put("premature", jsonData.getString("premature"));

        Integer ageTo = jsonData.getInteger("ageTo");
        Integer ageFrom = jsonData.getInteger("ageFrom");

        Calendar to = Calendar.getInstance();
        if (ageTo != null) {
            to.add(Calendar.MONTH, -ageTo);
            paramMap.put("ageTo", DateUtil.getDate_8(to.getTime()));
        }

        Calendar from = Calendar.getInstance();
        if (ageFrom != null) {
            from.add(Calendar.MONTH, -ageFrom);
            // from.set(Calendar.DAY_OF_MONTH,
            // from.getActualMaximum(Calendar.DAY_OF_MONTH));
            paramMap.put("ageFrom", DateUtil.getDate_8(from.getTime()));
        }

        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }
        // 可以查询队列中正常状态患者，也可查询扫码建档待审核状态的患者
        String confirmFlag = jsonData.getString("confirmFlag");
        if (StringUtils.isNotEmpty(confirmFlag)) {
            paramMap.put("confirmFlag", confirmFlag);
        }
        paramMap.put("taskAuditStatus", jsonData.getString("taskAuditStatus"));

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }
        HashMap<String, Object> retMap = patientSerivce.qryPatientQueueSchemeList(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }

        return retMap;
    }

    // 患者随访记录查询
    @ResponseBody
    @RequestMapping("/patientFollowDealRecordList")
    public Map<String, Object> listPatientFollowDealRecord(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in listPatientFollowDealRecord----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无flag节点！"));
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("userName", userName);
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 检测日期对应年龄
        Integer chkAgeTo = jsonData.getInteger("chkAgeTo");
        Integer chkAgeFrom = jsonData.getInteger("chkAgeFrom");
        if (null != chkAgeTo && chkAgeTo >= 0) {
            paramMap.put("chkAgeTo", chkAgeTo);
        }
        if (null != chkAgeFrom && chkAgeFrom >= 0) {
            paramMap.put("chkAgeFrom", chkAgeFrom);
        }
        paramMap.put("taskAgeFlag", jsonData.getString("taskAgeFlag"));

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("sourceType", jsonData.getString("opType"));
        paramMap.put("premature", jsonData.getString("premature"));
        paramMap.put("qryEndTime", jsonData.getString("qryEndTime"));
        paramMap.put("qryStartTime", jsonData.getString("qryStartTime"));
        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }
        // 可以查询正常状态的任务，也可查询扫码建档待审核状态的任务
        String taskAuditStatus = jsonData.getString("taskAuditStatus");
        if (StringUtils.isNotEmpty(taskAuditStatus)) {
            paramMap.put("taskAuditStatus", taskAuditStatus);
        }

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        HashMap<String, Object> retMap = patientSerivce.qryPatientQueueSchemeList(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        retMap.put("success", true);

        return retMap;
    }

    // 当前登录账号随访患者统计数据（工作站）
    @ResponseBody
    @RequestMapping("/patientQueueStatisticsQuery")
    public ResultModel<HashMap<String, Object>> qryPatientQueueStatistics(@RequestBody String arg,
                                                                          HttpServletRequest request) throws Exception {
        logger.warn("in qryPatientQueueStatistics----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        Integer schemeBusiType = (Integer) jsonData.getInteger("schemeBusiType");
        if (null == schemeBusiType) {
            // 默认查询随访统计数据
            schemeBusiType = Constants.SCHEME_BUSI_TYPE_0;
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("schemeBusiType", schemeBusiType);

        HashMap<String, Object> retMap = patientSerivce.qryPatientQueueStatistics(paramMap);
        logger.warn("patientQueueStatisticsQuery out ==" + retMap.toString());

        return new ResultModel<HashMap<String, Object>>(retMap);
    }

    // 患者数据统计（医生主页）
    @ResponseBody
    @RequestMapping("/patientStatisticsQuery")
    public ResultModel<Map<String, Object>> qryPatientStatistics(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in qryPatientStatistics----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 租户id
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("deptId", deptId);
        List<String> busiCategorys = new ArrayList<String>();
        List<String> testbusiCategorys = new ArrayList<String>();
        if (null != paramMap.get("busiCategory") && !"".equals(paramMap.get("busiCategory"))) {
            if (Constants.PATIENT_ACTIVE_BUSI_TYPE_6.equals((String) paramMap.get("busiCategory"))) {
                // 监测数据 用户自己上传部分 无队列或租户信息
                testbusiCategorys.add((String) paramMap.get("busiCategory"));
                paramMap.put("testbusiCategorys", busiCategorys);
            }
            busiCategorys.add((String) paramMap.get("busiCategory"));
            paramMap.put("busiCategorys", busiCategorys);
        } else {
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_1);
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_2);
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_3);
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_4);
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_5);
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_7);
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_8);
            busiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_9);
            busiCategorys.add(Constants.PATIENT_ACTIVE_APP_LOGIN);
            paramMap.put("busiCategorys", busiCategorys);

            // 患者自己上传监测数据 没有保存队列和租户 需分条件开查询
            testbusiCategorys.add(Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
            paramMap.put("testbusiCategorys", busiCategorys);
        }

        Map<String, Object> retMap = patientSerivce.qryPatientStatistics(paramMap);
        logger.warn("qryPatientStatistics out ==" + retMap.toString());

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 患者所在队列的任务list
    @ResponseBody
    @RequestMapping("/patientTaskListQuery")
    public ResultModel<HashMap<String, Object>> qryPatientTaskList(@RequestBody String arg) throws Exception {
        logger.warn("in qryPatientTaskList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        String ptSchemeId = jsonData.getString("patientSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者所在队列id或值为空！"));
        }
        String queueId = jsonData.getString("followQueueId");
        String userId = jsonData.getString("patientId");
        paramMap.put("ptSchemeId", ptSchemeId);
        paramMap.put("userId", userId);
        paramMap.put("queueId", queueId);
        // paramMap.put("orderBy", jsonData.get("orderBy"));// 排序，需要统一规则，这里先写死
        paramMap.put("seqNoOrderAsc", "1");
        paramMap.put("taskFlag", jsonData.getString("taskFlag"));// 默认不传（查询截止到当天可以进行的任务），传了则查询所有任务
        paramMap.put("currDate", DateUtil.getCurrDate());
        if (!StringUtils.isEmpty(jsonData.getString("seqNo"))) {
            paramMap.put("seqNo", jsonData.getInteger("seqNo"));
        }
        if (null == paramMap.get("taskFlag")) {
            if (StringUtils.isNotEmpty(queueId)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", queueId);
                FollowQueue queue = followQueueSerivce.getQueueDetailByQueueId(map);
                if (null == queue) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
                }
                String queueUserType = queue.getQueueUsertype();
                if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
                    paramMap.put("taskFlag", "1");
                }
            }
        }
        List<Object> ptList = patientSerivce.qryPatientTaskList(paramMap);
        HashMap<String, Object> retMap = new HashMap<String, Object>();
        int total = 0;
        if (null != ptList) {
            total = ptList.size();
        }
        retMap.put("total", total);
        retMap.put("rows", ptList);

        return new ResultModel<HashMap<String, Object>>(retMap);
    }

    /**
     * 查询患者所在队列某项任务的具体任务内容list。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     * Updated by Michael on 2022/9/29.
     * 增加GY3Y对应的需求。
     */
    @ResponseBody
    @RequestMapping("/patientTaskContentDataQuery")
    public ResultModel<HashMap<String, Object>> qryPatientTaskContentList(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in qryPatientTaskContentList----arg==" + arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        String taskId = jsonData.getString("ptTaskId");
        if (null == taskId || "".equals(taskId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者任务id或值为空！"));
        }
        String queueId = jsonData.getString("followQueueId");
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        final String tenantId = (String) sessionMap.get("tenantId");// 租户id
        int groupType = (Integer) sessionMap.get("groupType");// 组织类型
        String rootGroupId = (String) sessionMap.get("rootGroupId");// 组织id
        String refTenantId = (String) sessionMap.get("refTenantId");//关联上级医院id

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("authorId", authorId);
        paramMap.put("authorName", authorName);
        paramMap.put("tenantId", tenantId);
        paramMap.put("groupType", groupType);
        paramMap.put("rootGroupId", rootGroupId);
        paramMap.put("taskId", taskId);
        paramMap.put("queueId", queueId);
        HashMap<String, Object> retMap = patientSerivce.qryPatientContentList(paramMap);

        //获取建党信息的体质信息
        PhysiqueInfo physiqueInfo = patientSerivce.getPhysiqueInfo(taskId);
        retMap.put("physique",physiqueInfo);

        if (queueId.contains("naocuzhong")){
            String patientId = getPatientIdByPtTaskId(taskId);
            HashMap<String, Object> patientMap = new HashMap<>();
            patientMap.put("userId",patientId);
            Patient patient = patientSerivce.getPatient(patientMap);
            if (ObjectUtil.isNotEmpty(patient)){
                retMap.put("patient",patient);
            }
            if (patientId!=null){
                //根据patientId获取脑卒中量表的测量记录
                Map<String,Object> resMap = patientSerivce.getNirnAssessData(patientId);
                retMap.put("nirnAssessData",resMap);
            }
        }

        if(queueId.equals("zdyfynewJCEBjcbjqueue")){
            retMap.put("taskId", taskId);
            izdyService.Day42CopyValue(retMap);
        }

        //特殊处理：广医三院的需求。
        if (tenantId.equals("gzykdxfsdsyyta001"))    {
            Map<String,Object> gy3yMap  = patientSwitchService.dealGy3yContent(retMap, taskId);
        }

        return new ResultModel(retMap);
    }

    private String getPatientIdByPtTaskId(String taskId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("taskId",taskId);
        List<PatientTask> taskList = patientTaskDao.selectById(map);
        if (taskList !=null && taskList.size()>0){
            PatientTask patientTask = taskList.get(0);
            return patientTask.getUserId();
        }
        return null;
    }

    // 患者任务内容更新
    @ResponseBody
    @RequestMapping("/patientTaskContentDataModify")
    public ResultModel<HashMap<String, Object>> savePatientContentInfo(@RequestBody String arg,
                                                                       HttpServletRequest request) throws Exception {
        logger.warn("in savePatientContentInfo----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        JSONObject jsonTask = jsonData.getJSONObject("task");
        if (null == jsonTask) {
            // 前台必须传task节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无task节点！"));
        }
        JSONObject jsonQuestions = jsonData.getJSONObject("questiones");

        JSONObject jsonOpInfo = jsonData.getJSONObject("oprInfo");
        if (null == jsonOpInfo) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无oprInfo节点！"));
        }
        String opCode = jsonOpInfo.getString("opCode");
        if (null == opCode || "".equals(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码节点！"));
        }
        String queueId = jsonOpInfo.getString("followQueueId");
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无队列id节点！"));
        }
        String ptSchemeId = jsonOpInfo.getString("ptSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        String userId = jsonOpInfo.getString("patientId");
        if (null == userId || "".equals(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者id未传或值为空！"));
        }

        // 入参中没有，从问卷答案中获取
        Map<String, Object> quesMap = (JSONObject) jsonData.getJSONObject("questiones");
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");// 租户id
        paramMap.put("authorName", authorName);
        // 修改手机号同步app 使用
        paramMap.put("deptId", deptId);

        String taskId = jsonTask.getString("ptTaskId");
        if (null == taskId || "".equals(taskId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者任务id或值为空！"));
        }
        String seqNo = jsonTask.getString("seqNo");
        boolean initTask = false;// 建档任务
        if (!StringUtils.isEmpty(seqNo)) {
            if (seqNo.equals("" + Constants.TASK_SEQ_FOR_INIT)) {
                initTask = true;
            }
        }

        String finishDate = jsonTask.getString("finishDate");
        if (!initTask && StringUtils.isBlank(finishDate)) {
            // 建档可以不传随访日期
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "未传入随访日期或值为空！"));
        }
        String updateAuname = jsonTask.getString("updateAuname");
        if (StringUtils.isBlank(updateAuname)) {
            updateAuname = authorName;
        }

//        String sendFlag = jsonData.getString("sendFlag");
//        if (StringUtils.isBlank(sendFlag)) {
//            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，是否发送通知标志未传或值为空！"));
//        }
        JSONArray ptContentIds = jsonTask.getJSONArray("ptContentIds");
        if (null == ptContentIds || 0 == ptContentIds.size()) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者任务内容id节点或值为空！"));
        }
        String contentData = jsonData.getString("questiones");
        if (null == contentData || "".equals(contentData)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入任务内容报文或值为空！"));
        }
        // 生物样本采集信息（安医大需求）
        JSONArray sampleList = jsonData.getJSONArray("sampleList");
        if (null != sampleList) {
            paramMap.put("sampleList", sampleList);
        }

        String currTime = jsonOpInfo.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }

        String taskNote = jsonTask.getString("taskNote");
        if (StringUtils.isBlank(taskNote)) {
            if (null != quesMap && 0 != quesMap.size()) {
                taskNote = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_FOLLOW_NOTE);
            }
        }

        String nextDate = jsonTask.getString("nextDate");
        if (StringUtils.isBlank(nextDate)) {
            if (null != quesMap && 0 != quesMap.size()) {
                nextDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_FOLLOW_DATE);
            }
        }

        String nextAddress = jsonTask.getString("nextAddress");
        if (StringUtils.isBlank(nextAddress)) {
            if (null != quesMap && 0 != quesMap.size()) {
                nextAddress = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_FOLLOW_ADDRESS);
            }
        }
        // 来源渠道
        String sourceType = jsonOpInfo.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            // 默认web端门诊渠道
            sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        }
        paramMap.put("sourceType", sourceType);

        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        paramMap.put("taskId", taskId);
        paramMap.put("contentData", jsonData.getJSONObject("questiones"));
        paramMap.put("ptSchemeId", ptSchemeId);
        paramMap.put("userId", userId);
        paramMap.put("updateTime", currTime);
        paramMap.put("updateAccept", updateAccept);
        paramMap.put("authorId", author);
        paramMap.put("tenantId", tenantId);
        paramMap.put("opCode", opCode);
        paramMap.put("queueId", queueId);
        paramMap.put("opNote", jsonOpInfo.getString("opNote"));
        paramMap.put("opType", jsonOpInfo.getString("opType"));
        paramMap.put("ptContentIds", ptContentIds);
        paramMap.put("updateAuname", updateAuname);
        paramMap.put("finishDate", finishDate);
        paramMap.put("taskNote", taskNote);
        paramMap.put("nextDate", nextDate);
        paramMap.put("nextAddress", nextAddress);

        // 问卷类型，这里先写死0代表门诊问卷
        paramMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);
        patientSerivce.modTaskContentData(paramMap);

        //Edit by jiangq on 2023年09月04日 随访数据复制到其他队列，同一个窗口期内的日期对比复制
        String conditionIn = "{\"data\":{\"systemType\":\"00\",\"flag\":\"2\",\"rows\":16,\"patientId\": \""+ userId + "\" }}";

        ResultModel<HashMap<String, Object>> resMap = this.qryPatientQueueSchemeList(conditionIn, request);
        HashMap<String, Object> data = resMap.getData();
        List rows = (List) data.get("rows");
        HashMap<String, Object> paraMap = new HashMap<>();
        if(rows.size() > 0){
            for (Object row : rows) {
                HashMap map = (HashMap) row;
                List<PatientContentData> addcontentDatas = new ArrayList<>();
                //当前队列的随访任务
                paraMap.put("taskFlag", "1");
                paraMap.put("ptSchemeId", ptSchemeId);
                List<PatientTask> oldPatientTasks = patientTaskDao.selectByPtSchemeId(paraMap);
                //新的随访任务
                String newPtSchemeId = (String) map.get("patientSchemeId");
                if(ptSchemeId.equals(newPtSchemeId)){
                    continue;
                }
                paraMap.put("ptSchemeId", newPtSchemeId);
                List<PatientTask> newPatientTasks = patientTaskDao.selectByPtSchemeId(paraMap);
                String newTaskId = null;
                for (PatientTask newPatientTask : newPatientTasks) {
                    Date executeTime = DateUtil.getDate_8(newPatientTask.getExecuteTime());
                    for (PatientTask task : oldPatientTasks) {
                        if(DateUtil.getDate_8(task.getBeginTime()).getTime() <= executeTime.getTime() && DateUtil.getDate_8(task.getEndTime()).getTime() >= executeTime.getTime() && task.getSeqNo() != 0){
                            newTaskId = newPatientTask.getId();
                            HashMap<String,Object> mapIn  = new HashMap<>();
                            mapIn.put("taskId", task.getId());
                            List<PatientContentData> contentDataList = taskContentDAO.selectContentDataByTaskId(mapIn);
                            for (PatientContentData patientContentData : contentDataList) {
                                patientContentData.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
                                patientContentData.setTaskId(newTaskId);
                                patientContentData.setPtSchemeid(newPtSchemeId);
                                patientContentData.setQueueId(task.getQueueId());
                            }
                            addcontentDatas.addAll(contentDataList);
                        }
                    }
                }
                addcontentDatas = addcontentDatas.stream().filter(item -> !item.getQuestionAnswer().equals("") && item.getQuestionAnswer() != null).collect(Collectors.toList());
                if (!addcontentDatas.isEmpty()) {
                    taskContentDAO.savePatientTaskContentDataBatch(addcontentDatas);
                }
            }
        }

        String sendMsg = null;
        String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();
        if (("0").equals(seqNo)) {
            //修改用户下所有手机号
            String phone = quesMap.get("Pub1100001").toString();
            patientPhoneService.updatePatientPhone(tenantId,userId,phone,author);
            // type=12 患者修改信息推送
            int type = UPDATE_USER;
            // system=1 2.0系统
            int system = 1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type",type);
            jsonObject.put("userId",userId);
            jsonObject.put("tenantId",tenantId);
            jsonObject.put("system",system);
            jsonObject.put("deptId",deptId);
            jsonObject.put("platType",Integer.parseInt(platType));
            sendMsg = jsonObject.toJSONString();
            if(StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl"))) {
                HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl"), sendMsg);
            }
//            if ((sendFlag.equalsIgnoreCase("y") || sendFlag.equalsIgnoreCase("yes") || sendFlag.equalsIgnoreCase("true")) && StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl"))) {
//                HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl"), sendMsg);
//            }
        } else {
            // 门诊问卷保存成功后推送任务id到小程序
            // type=2 诊后指导推送
            int type = 2;

            if(!platType.equals("0")){
               // sendMsg = "{\"type\":" + type + ",\"taskId\":\"" + taskId + "\",\"platType\":"+ platType+"}";
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type",type);
                jsonObject.put("taskId",taskId);
                jsonObject.put("platType",Integer.parseInt(platType));
                jsonObject.put("deptId",deptId);
                sendMsg = jsonObject.toJSONString();
                HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl"), sendMsg);
//                if ((sendFlag.equalsIgnoreCase("y") || sendFlag.equalsIgnoreCase("yes") || sendFlag.equalsIgnoreCase("true")) && StringUtils.isNotBlank(PropertiesUtils.getProperty("redirectUrl"))) {
//                    HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl"), sendMsg);
//                }
            }
            if (ObjectUtil.isNotEmpty(jsonQuestions)) {
                String scaleAssessStatus = (String)jsonQuestions.get("scaleAssessStatus");
                if (StringUtils.isNotEmpty(scaleAssessStatus)){
                    String accessStatus = null;
                    if (scaleAssessStatus.contains("低危")){
                        accessStatus = "1";
                    }
                    if (scaleAssessStatus.contains("中危")){
                        accessStatus = "2";
                    }
                    if (scaleAssessStatus.contains("高危")){
                        accessStatus = "3";
                    }
                    if (StringUtils.isNotEmpty(accessStatus)){
                        patientSerivce.updateAccessStatus(userId,accessStatus);
                    }
                }
            }
        }

        HashMap<String, Object> retMap = new HashMap<String, Object>();
        return new ResultModel<HashMap<String, Object>>(retMap);
    }

    // 患者专科袋问卷类别查询
    @ResponseBody
    @RequestMapping("/patientContentCategoryListQuery")
    public ResultModel<HashMap<String, Object>> qryPatientContentCategoryList(@RequestBody String arg)
            throws Exception {
        logger.warn("in qryPatientContentCategoryList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        String ptSchemeId = jsonData.getString("patientSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        // 默认不查询建档任务信息对应的问卷，若传入该参数则查询
        paramMap.put("patientAddFlag", jsonData.getString("patientAddFlag"));
        paramMap.put("ptSchemeId", ptSchemeId);
        // paramMap.put("taskTypeRev",
        // Constants.TASK_TYPE_NONSCHEME_REALTIME);// 主诉登记不展示
        paramMap.put("ptTaskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 暂时只展示门诊任务
        HashMap<String, Object> retMap = patientSerivce.qryPatientContentCategory(paramMap);

        return new ResultModel<HashMap<String, Object>>(retMap);
    }

    /**
     * 患者专科袋详情查询。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/patientContentDetailQuery")
    public ResultModel<Map<String, Object>> patientContentDetailQuery(@RequestBody String arg,
                                                                          HttpServletRequest request) throws Exception {
        logger.warn("in patientContentDetailQuery----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        String ptSchemeId = jsonData.getString("patientSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        String conTemplVerId = jsonData.getString("questionnaireId");
        if (null == conTemplVerId || "".equals(conTemplVerId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入问卷模板id或值为空！"));
        }
        String patientId = jsonData.getString("patientId");
        if (StringUtils.isEmpty(patientId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入患者id或值为空！"));
        }
        // session信息
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        // 默认不查询建档任务信息对应的问卷，若传入该参数则查询
        paramMap.put("conTemplVerId", conTemplVerId);
        paramMap.put("ptSchemeId", ptSchemeId);
        paramMap.put("patientId", patientId);

        Map<String, Object> queueInMap = new HashMap<>();
        queueInMap.put("userId", patientId);
        List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(queueInMap);
        if (queueSchemeList!=null && queueSchemeList.size()>0){
            PatientQueueScheme queueScheme = queueSchemeList.get(0);
            paramMap.put("queueId", queueScheme.getQueueId());
        }

        HashMap<String, Object> retMap = patientSerivce.qryPatientContentDetail(paramMap);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    /**
     * 根据GY3Y的需求，升级为简明随访病历。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/querySimpleMR")
    public ResultModel<Map<String, Object>> querySimpleMR(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in querySimpleMR----arg==" + arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,  "入参节点错误，无data节点！"));
        }

        final String ptSchemeId = jsonData.getString("patientSchemeId");
        if (StringUtils.isEmpty(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,  "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        final String conTemplVerId = jsonData.getString("questionnaireId");
        if (StringUtils.isEmpty(conTemplVerId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,  "入参节点错误，未传入问卷模板id或值为空！"));
        }
        final String patientId = jsonData.getString("patientId");
        if (StringUtils.isEmpty(patientId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,  "入参节点错误，未传入患者id或值为空！"));
        }

        Map<String, Object> paraMap = new HashMap<String, Object>();
        //session信息.
        final Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");
        paraMap.put("authorId", authorId);
        paraMap.put("tenantId", tenantId);

        // 默认不查询建档任务信息对应的问卷，若传入该参数则查询
        paraMap.put("conTemplVerId", conTemplVerId);
        paraMap.put("ptSchemeId", ptSchemeId);
        paraMap.put("patientId", patientId);

        Map<String, Object> retMap = patientSwitchService.queryAllAnswerByPatient(paraMap);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 患者操作记录查询（如今日门诊记录等）
    @ResponseBody
    @RequestMapping("/patientOperateListQuery")
    public ResultModel<Map<String, Object>> qryPatientOperateList(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in qryPatientOperateList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            // 默认查询今日门诊记录
            flag = "0";
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("userName", userName);
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);
        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }
        if (!StringUtils.isEmpty(jsonData.getString("queueId"))) {
            paramMap.put("queueId", jsonData.getString("queueId"));
        }
        // 方案业务类型，0:科研随访方案；1:门诊诊疗方案；2:待扩展...可不传，不传的情况下默认为0（为兼容老的随访系统）
        Integer schemeBusiType = jsonData.getInteger("schemeBusiType");
        if (null == schemeBusiType) {
            schemeBusiType = Constants.SCHEME_BUSI_TYPE_0;
        }
        paramMap.put("schemeBusiType", schemeBusiType);

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        Integer ageTo = jsonData.getInteger("ageTo");
        Integer ageFrom = jsonData.getInteger("ageFrom");

        Calendar to = Calendar.getInstance();
        if (ageTo != null) {
            to.add(Calendar.MONTH, -ageTo);
            paramMap.put("ageTo", DateUtil.getDate_8(to.getTime()));
        }

        Calendar from = Calendar.getInstance();
        if (ageFrom != null) {
            from.add(Calendar.MONTH, -ageFrom);
            // from.set(Calendar.DAY_OF_MONTH,
            // from.getActualMaximum(Calendar.DAY_OF_MONTH));
            paramMap.put("ageFrom", DateUtil.getDate_8(from.getTime()));
        }

        // 该租户下的记录是否需要分页
        Map<String, Object> qryMapIn = new HashMap<String, Object>();
        qryMapIn.put("tenantId", tenantId);
        qryMapIn.put("type", Constants.TODAY_OUTPATIENT_RECORD_ISPAGING_TYPE);
        List<Map<String, Object>> retList = confCacheDAO.selectBsStaticParamByTenant(qryMapIn);
        if (CollectionUtils.isNotEmpty(retList)) {
            // 配置了则不分页
            paramMap.put("noPaging", "Y");
        }
        paramMap.put("end", 1000);

        Map<String, Object> retMap = new HashMap<String, Object>();
        if (Constants.SCHEME_BUSI_TYPE_0 == schemeBusiType) {
            retMap = patientSerivce.qryPatientOperationList(paramMap);
        } else if (Constants.SCHEME_BUSI_TYPE_1 == schemeBusiType) {
            retMap = patientTreatService.listPtTrOperation(paramMap);
        } else if (Constants.SCHEME_BUSI_TYPE_2 == schemeBusiType) {
            retMap = patientSerivce.qryPatientOperationList(paramMap);
        } else {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_SCHEME_BUSITYPE_INCOMPATIBLE,
                    "暂不支持该方案业务类型: [" + schemeBusiType + "]！"));
        }
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 患者操作记录查询（如主诉登记等）
    @ResponseBody
    @RequestMapping("/patientOnlineOperateListQuery")
    public Map<String, Object> listPatientOnlineOperateList(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in listPatientOnlineOperateList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无flag节点！"));
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("userName", userName);
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);
        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }
        if (!StringUtils.isEmpty(jsonData.getString("queueId"))) {
            paramMap.put("queueId", jsonData.getString("queueId"));
        }
        if (!StringUtils.isEmpty(jsonData.getString("qryEndTime"))) {
            paramMap.put("qryEndTime", jsonData.getString("qryEndTime"));
        }
        if (!StringUtils.isEmpty(jsonData.getString("qryStartTime"))) {
            paramMap.put("qryStartTime", jsonData.getString("qryStartTime"));
        }
        paramMap.put("taskNotNull", "1");

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }
        HashMap<String, Object> retMap = patientSerivce.qryPatientOperationList(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        retMap.put("success", true);

        return retMap;
    }

    /**
     * 查询主诉（登记）任务内容操作详情
     *
     * @param
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ptOnlineOprDetailQuery")
    public Object getPtOnlineOprDetail(@RequestBody String jsonStr, HttpServletRequest request) throws Exception {
        logger.info("in getPtOnlineOprDetail----arg==" + jsonStr);

        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理

        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        map.put("authorId", authorId);
        map.put("tenantId", tenantId);

        String patientId = requestParam.getString("patientId");
        if (StringUtils.isEmpty(patientId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者不能为空!");
        }
        String queueId = requestParam.getString("queueId");
        if (StringUtils.isEmpty(queueId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列id不能为空!");
        }
        String type = requestParam.getString("type");
        if (StringUtils.isEmpty(type)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，问卷类型不能为空!");
        }
        String taskId = requestParam.getString("taskId");
        if (StringUtils.isEmpty(taskId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，任务id不能为空!");
        }
        String updateAccept = requestParam.getString("updateAccept");
        if (StringUtils.isEmpty(updateAccept)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作流水不能为空!");
        }

        map.put("patientId", patientId);
        map.put("queueId", queueId);
        map.put("type", type);
        map.put("taskId", taskId);
        map.put("updateAccept", updateAccept);
        Map<String, Object> rspMap = appUserService.getPtOnlineOperateDetail(map);

        return new ResultModel<Map<String, Object>>(rspMap);
    }

    /**
     * @param arg
     * @param request
     * @return
     * @throws Exception
     * @desc 患者主页 患者详细信息查询 包括 患者所在队列(如有多个，需根据当前用户权限筛选返回)
     */
    @ResponseBody
    @RequestMapping("/patientDetailsQuery")
    public ResultModel<Map<String, Object>> qryPatientDetails(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        Map<String, Object> retMap = null;
        logger.warn("in patientDetailsQuery----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        String userId = jsonData.getString("userId");
        if (StringUtils.isBlank(userId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，患者ID不能为空");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("authorId", authorId);
        map.put("tenantId", tenantId);
        map.put("userId", userId);
        retMap = patientSerivce.qryPatientDetail(map);
        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 根据用户id+患者队列实例id查询患者信息
    @ResponseBody
    @RequestMapping("/patientInfoQueryByPtId")
    public ResultModel<Map<String, Object>> qryPatientByUserIdAndPtSchemeId(@RequestBody String arg,
                                                                            HttpServletRequest request) throws Exception {
        logger.warn("in qryPatientByUserIdAndPtSchemeId----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        Map<String, Object> servParamMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        servParamMap.put("authorId", authorId);
        servParamMap.put("tenantId", tenantId);

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        String patientId = jsonData.getString("patientId");
        if (null == patientId || "".equals(patientId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入患者id或值为空！"));
        }
        String ptSchemeId = jsonData.getString("ptSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        servParamMap.put("patientId", patientId);
        servParamMap.put("ptSchemeId", ptSchemeId);

        Map<String, Object> retMap = patientSerivce.getPatientInfoByUserIdAndPtSchemeId(servParamMap);
        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 根据用户id查询患者信息
    @ResponseBody
    @RequestMapping("/patientInfoPtId")
    public ResultModel<Map<String, Object>> qryPatientInfoPtId(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in qryPatientInfoPtId----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        Map<String, Object> servParamMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        servParamMap.put("authorId", authorId);
        servParamMap.put("tenantId", tenantId);

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        String patientId = jsonData.getString("patientId");
        if (null == patientId || "".equals(patientId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入患者id或值为空！"));
        }
        servParamMap.put("patientId", patientId);
        servParamMap.put("showFlag", jsonData.getString("showFlag"));
        /* 2017-10-07 add by wuyz */
        servParamMap.put("examinationPaperName", jsonData.getString("examinationPaperName"));
        Map<String, Object> retMap = patientSerivce.getPatientInfoByUserId(servParamMap);
        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 数据中心随访患者信息查询
    @ResponseBody
    @RequestMapping("/patientListDataCenterQuery")
    public Map<String, Object> qryPatientListDataCenter(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in qryPatientListDataCenter----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        String userStatus = jsonData.getString("userStatus");
        if(StringUtils.isNotEmpty(userStatus)){
            paramMap.put("userStatus", userStatus);
        };


        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("userName", userName);
            //增加通过拼音查询用户
            paramMap.put("namePinyin", userName.toLowerCase() + "%");
            //名字简拼
            paramMap.put("nameInitial", userName.toLowerCase() + "%");
        }
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("qryEndTime", jsonData.getString("qryEndTime"));
        paramMap.put("qryStartTime", jsonData.getString("qryStartTime"));
        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }
        String appActFlag = jsonData.getString("appActFlag");
        if (StringUtils.isNotEmpty(appActFlag)) {
            paramMap.put("appActFlag", appActFlag);
        }

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        Map<String, Object> retMap = patientSerivce.qryPatientListDataCenter(paramMap);
        //如果是预诊队列已完成状态需要展示已加入队列
        if("7".equals(userStatus)){
            patientSwitchService.setExistQueue(retMap);
        }
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        retMap.put("success", true);

        return retMap;
    }

    // 患者添加（该接口暂时未启用）
    @ResponseBody
    @RequestMapping("/register/patientForQRCode")
    public ResultModel<Map<String, Object>> patientForQRCode(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in patientForQRCode----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

        // 参数校验后续补充
        String deptId = jsonData.getString("deptId");
        if (StringUtils.isBlank(deptId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传科室id或值为空！"));
        }

        // 根据deptId查询 默认队列信息 //宝宝 产妇
        String defaultQueueId = null; // 默认产妇队列
        String defaultBabyQueueId = null;// 默认宝宝队列
        Map<String, Object> queueParam = new HashMap<String, Object>();
        queueParam.put("deptId", deptId);
        queueParam.put("defaultOption", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
        queueParam.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
        List<FollowQueue> queueList = followQueueService.getDefaultQueueByDeptId(queueParam);
        if (!CollectionUtils.isEmpty(queueList)) {
            for (int i = 0; i < queueList.size(); i++) {
                if (Constants.QUEUE_USER_TYPE_BABY.equals(queueList.get(i).getQueueUsertype())) {
                    defaultBabyQueueId = queueList.get(i).getId();
                } else if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueList.get(i).getQueueUsertype())) {
                    defaultQueueId = queueList.get(i).getId();
                }
            }
        }

        Map<String, Object> servParamMap = jsonData;

        String userType = jsonData.getString("userType");
        if (StringUtils.isBlank(userType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者类型为空！"));
        }

        String phoneNo = jsonData.getString("phoneNo");
        if (StringUtils.isBlank(phoneNo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，服务号码为空！"));
        }

        String userName = jsonData.getString("userName");
        if (StringUtils.isBlank(userName)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，就诊人姓名为空！"));
        }

        /*
         * String expectedDay = jsonData.getString("expectedDay"); if
         * (StringUtils.isBlank(expectedDay)) { throw (new
         * AppException(ErrorCode.
         * FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
         * "入参节点错误，当为用户类型为宝宝时,预产期不能为空！")); }
         */

        // 校验预产期是否传入
        Patient pt = new Patient(); // 产妇
        Patient baby = new Patient();

        String gender = "";
        String birthday = "";
        String pregnancyWeek = ""; // 孕周

        String childbirth = "";
        JSONObject babyInfo = null;
        String babyName = "";
        String babyGender = "";
        String babyBirthday = "";
        String expectedDay = "";
        // 来源渠道，入参若无，则默认扫码主诉渠道
        String sourceType = (String) servParamMap.get("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            sourceType = Constants.PATIENT_SOURCE_TYPE_SCAN_SYMPTOM;// 扫码主诉渠道
        }

        if (userType.equals(Constants.QUEUE_USER_TYPE_BABY)) {
            babyGender = jsonData.getString("gender");
            babyBirthday = jsonData.getString("birthday");
            pregnancyWeek = jsonData.getString("pregnancyWeek");
            if (StringUtils.isBlank(birthday)) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        "入参节点错误，当为用户类型为宝宝时,出生不能为空！"));
            }
            if (StringUtils.isBlank(gender)) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        "入参节点错误，当为用户类型为宝宝时,性别不能为空！"));
            }
            if (StringUtils.isBlank(pregnancyWeek)) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        "入参节点错误，当为用户类型为宝宝时,孕周不能为空！"));
            }

            if (StringUtils.isBlank(defaultBabyQueueId)) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
                        "该科室没有配置宝宝默认队列信息"));
            }

            baby.setUserName(userName);
            baby.setPhoneNo(phoneNo);
            baby.setFirstName(userName.substring(0, 1));
            baby.setCreateTime(currTime);
            baby.setUpdateTime(currTime);
            baby.setCreateAuthor("");
            baby.setBirthday(babyBirthday);
            // pt.setExpectedDay(expectedDay);
            baby.setPregnancyDay(Integer.parseInt(pregnancyWeek));
            baby.setGender(babyGender);
            baby.setUserType(userType);
            baby.setSourceType(sourceType); // 扫码建档
            // 根据生日和预产期计算孕周
            /*
             * int pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday,
             * expectedDay); pt.setPregnancyDay(pregnancyDay);
             */

        } else if (userType.equals(Constants.QUEUE_USER_TYPE_PARTURIENT)) {
            childbirth = jsonData.getString("childbirth");
            pregnancyWeek = jsonData.getString("pregnancyWeek");

            if (StringUtils.isBlank(childbirth)) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        "入参节点错误，当为用户类型为产妇时,是否分娩不能为空！"));
            }

            pt.setUserName(userName);
            pt.setPhoneNo(phoneNo);
            pt.setFirstName(userName.substring(0, 1));
            pt.setCreateTime(currTime);
            pt.setUpdateTime(currTime);
            pt.setBirthday(birthday);
            // pt.setExpectedDay(expectedDay);
            pt.setGender(gender);
            pt.setUserType(userType);
            pt.setSourceType(sourceType); // 扫码建档

            if (Constants.PARTURIENT_CHILDBIRTH_YES.equals(childbirth)) {// 已分娩
                if (StringUtils.isBlank(pregnancyWeek)) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                            "入参节点错误，当为用户类型为产妇且已分娩时，孕周不能为空"));
                }

                pt.setPregnancyDay(Integer.parseInt(pregnancyWeek));
                babyInfo = jsonData.getJSONObject("babyInfo");
                if (null != babyInfo) {
                    babyName = babyInfo.getString("babyName");
                    babyGender = babyInfo.getString("babyGender");
                    babyBirthday = babyInfo.getString("babyBirthday");

                    if (StringUtils.isBlank(defaultQueueId)) {
                        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
                                "该科室没有配置宝宝默认队列信息"));
                    }

                    if (StringUtils.isBlank(defaultBabyQueueId)) {
                        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
                                "该科室没有配置产妇默认队列信息"));
                    }

                    baby.setUserName(babyName);
                    baby.setPhoneNo(phoneNo);
                    baby.setFirstName(babyName.substring(0, 1));
                    baby.setCreateTime(currTime);
                    baby.setUpdateTime(currTime);
                    baby.setCreateAuthor("");
                    baby.setBirthday(babyBirthday);
                    // pt.setExpectedDay(expectedDay);
                    baby.setPregnancyDay(Integer.parseInt(pregnancyWeek));
                    baby.setGender(babyGender);
                    baby.setUserType(userType);
                    baby.setSourceType(sourceType); // 扫码建档
                    // baby.setRelevantId(relevantId);
                }
            } else {
                if (StringUtils.isBlank(defaultBabyQueueId)) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_DEPARTMENT_DEFAULT_QUEUE_NOT_EXIST,
                            "该科室没有配置产妇默认队列信息"));
                }
                expectedDay = jsonData.getString("expectedDay");
                if (StringUtils.isBlank(expectedDay)) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                            "入参节点错误，当为用户类型为产妇且未分娩时，预产期不能为空"));
                }
                pt.setExpectedDay(expectedDay);
            }
        } else {
            //
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "用户类型值不正确"));
        }

        servParamMap.put("patient", pt);
        servParamMap.put("patientBaby", baby);

        servParamMap.put("defaultBabyQueueId", defaultBabyQueueId);
        servParamMap.put("queueId", defaultQueueId);//

        servParamMap.put("updateTime", currTime);
        servParamMap.put("updateAccept", updateAccept);
        servParamMap.put("opCode", "1000");
        servParamMap.put("opNote", "患者通过二维码扫码进行建档操作");
        servParamMap.put("opType", "1");// 患者自助
        servParamMap.put("sourceType", sourceType);

        Map<String, Object> userMap = patientSerivce.registerPatientForQrcode(servParamMap);

        return new ResultModel<Map<String, Object>>(userMap);
    }

    /**
     * 患者数据样本采集标志位更新
     *
     * @param
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/patientSampleDataModify")
    public ResultModel<Object> updatePatientSampleData(HttpServletRequest request, @RequestBody String arg)
            throws Exception {
        logger.warn("in updatePatientSampleData----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "非json格式");
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        JSONObject jsonOpInfo = jsonData.getJSONObject("oprInfo");
        if (null == jsonOpInfo) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无oprInfo节点！"));
        }
        String opCode = jsonOpInfo.getString("opCode");
        if (null == opCode || "".equals(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码节点！"));
        }
        String opNote = jsonOpInfo.getString("opNote");
        if (null == opNote || "".equals(opNote)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作备注未传！"));
        }
        String opType = jsonOpInfo.getString("opType");
        if (null == opType || "".equals(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作类型未传！"));
        }

        JSONObject jsonSample = jsonData.getJSONObject("sampleInfo");
        if (null == jsonSample) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，无sampleInfo节点！"));
        }
        String ptSchemeId = jsonSample.getString("patientSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，患者队列实例id未传或值为空！"));
        }
        String userId = jsonSample.getString("patientId");
        if (null == userId || "".equals(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者id未传或值为空！"));
        }
        String queueId = jsonSample.getString("followQueueId");
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无队列id节点！"));
        }
        String sampleFlag = jsonSample.getString("sampleFlag");
        if (StringUtils.isEmpty(sampleFlag)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，采集标志位为空！"));
        }
        String sampleType = jsonSample.getString("sampleType");
        if (StringUtils.isEmpty(sampleType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，样本类型为空！"));
        }
        String sampleValue = jsonSample.getString("sampleValue");
        if (StringUtils.isEmpty(sampleValue)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，样本采集次数序号为空！"));
        }
        String sampleCode = jsonSample.getString("sampleCode");
        if (StringUtils.isEmpty(sampleCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无样本采集编码！"));
        }

        String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("updateTime", updateTime);
        map.put("updateAccept", updateAccept);

        map.put("sampleCode", sampleCode);
        map.put("sampleType", sampleType);
        map.put("sampleValue", sampleValue);
        map.put("userId", userId);
        map.put("queueId", queueId);
        map.put("ptSchemeId", ptSchemeId);
        map.put("sampleFlag", sampleFlag);
        map.put("opCode", opCode);
        map.put("opNote", opNote);
        map.put("opType", opType);

        map.put("authorId", authorId);
        map.put("tenantId", tenantId);
        map.put("authorName", authorName);

        Map<String, Object> mapOut = new HashMap<String, Object>();
        patientSerivce.updatePatientSampleData(map);

        return new ResultModel<Object>(mapOut);
    }

    // 患者任务内容更新
    @ResponseBody
    @RequestMapping("/saveBaseChild")
    public ResultModel<Map<String, Object>> saveBaseChild(@RequestBody String arg,
                                                          HttpServletRequest request) throws Exception {
        logger.warn("in saveBaseChild----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String queueId = jsonData.getString("followQueueId");
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无队列id节点！"));
        }
        String ptSchemeId = jsonData.getString("ptSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        String userId = jsonData.getString("patientId");
        if (null == userId || "".equals(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者id未传或值为空！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("authorName", authorName);

        String contentData = jsonData.getString("questiones");
        if (null == contentData || "".equals(contentData)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入任务内容报文或值为空！"));
        }

        String changeStatus = jsonData.getString("changeStatus");
        if (null == changeStatus || "".equals(changeStatus)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入转归类型报文或值为空！"));
        }

        // 来源渠道
        String sourceType = jsonData.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            // 默认web端门诊渠道
            sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        }
        paramMap.put("sourceType", sourceType);

        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
        paramMap.put("contentData", jsonData.getJSONObject("questiones"));
        paramMap.put("ptSchemeId", ptSchemeId);
        paramMap.put("userId", userId);
        paramMap.put("updateTime", currTime);
        paramMap.put("updateAccept", updateAccept);
        paramMap.put("updateAuthor", author);
        paramMap.put("tenantId", tenantId);
        paramMap.put("queueId", queueId);
        paramMap.put("changeStatus", changeStatus);

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap = baseChildService.changeStatus(paramMap);
        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 根据登陆信息查询该租户下的所有队列，用于队列模板下载批量建档
    @ResponseBody
    @RequestMapping("/getTenantQueueTemp")
    public ResultModel<List<Map<String, Object>>> getTenantQueueTemp(HttpServletRequest request) throws Exception {
        logger.warn("in getTenantQueueTemp");

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);
        paramMap.put("tempStatus", Constants.EXCEL_TEMPLATE_STATUS);

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = uploadExcelDAO.selectExcelTemp(paramMap);
        return new ResultModel<List<Map<String, Object>>>(list);
    }

    @ResponseBody
    @RequestMapping("/calcRecentUsers")
    public ResultModel CalcRecentUsers(HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);
        return new ResultModel(patientSerivce.calcRecentUsers(tenantId));
    }

    @ResponseBody
    @RequestMapping("/getPatientByGender")
    public ResultModel getPatientByGender(HttpServletRequest request) throws Exception {
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId", tenantId);
        List<Patient> patientList = patientSerivce.getPatientList(paramMap);
        HashMap<Object, Object> result = new HashMap<>();
        for (Patient patient : patientList) {
            if(result.containsKey(patient.getGender())){
                Integer o = (Integer) result.get(patient.getGender());
                o++;
                result.put(patient.getGender(), o);
            }else{
                result.put(patient.getGender(), 1);
            }
        }
        return new ResultModel(result);
    }

    // 患者结案
    @ResponseBody
    @RequestMapping("/closecase")
    public ResultModel<Object> closeCase(@RequestBody String arg,
                                                          HttpServletRequest request) throws Exception {
        logger.warn("in closeCase----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String queueId = jsonData.getString("followQueueId");
        if (null == queueId || "".equals(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无队列id节点！"));
        }

        String userId = jsonData.getString("patientId");
        if (null == userId || "".equals(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者id未传或值为空！"));
        }

        String ptSchemeId = jsonData.getString("ptSchemeId");
        if (null == ptSchemeId || "".equals(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入患者队列实例id或值为空！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("authorName", authorName);

        String contentData = jsonData.getString("closeReason");
        if (null == contentData || "".equals(contentData)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入结案原因或值为空！"));
        }

        String taskId = jsonData.getString("taskId");
        if (null == taskId || "".equals(taskId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入所属任务或值为空！"));
        }
        Map<String, Object> ptMap = new HashMap<String, Object>();
        ptMap.put("userId", userId);
        ptMap.put("tenantId", tenantId);
        Patient pt = patientSerivce.getPatient(ptMap);
        if (pt == null) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
        }
        //查询该病人是否已经结案
        HashMap<String, Object> map = new HashMap<String, Object>();
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("userId", userId);
        HashMap<String, Object> retMap = patientSerivce.pageList(paramMap);
        if(null != retMap ){
            List rows = (List) retMap.get("rows");
            if(rows.size() > 0){
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        "该患者已结案，请不要重复操作！"));
            }
        }

        FuClosecaseRecord temp = new FuClosecaseRecord();
        temp.setId(SeqUtil.getSeqNo());
        temp.setUserId(pt.getId());
        temp.setUserName(pt.getUserName());
        temp.setPhone(pt.getPhoneNo());
        temp.setGender(pt.getGender());
        temp.setBirthdate(DateUtil.getDate(pt.getBirthday()));
        temp.setCloseType(Constants.MANUAL_CLOSE);//手动中止
        temp.setTenantId(tenantId);
        temp.setCloseReason(jsonData.getString("closeReason"));
        temp.setCreateTime(new Date());
        temp.setQueueId(queueId);
        temp.setTaskId(taskId);
        temp.setCreater(authorId);
        temp.setPtSchemeid(ptSchemeId);
        fuClosecaseRecordService.insert(temp);
        return new ResultModel<Object>("");
    }

    @ResponseBody
    @RequestMapping("/getClosecaseData")
    public Map<String, Object> getClosecaseData(@RequestBody String arg,
                                         HttpServletRequest request) throws Exception {

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNum", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("patientName", userName);
        }
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);


        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }
        HashMap<String, Object> retMap = patientSerivce.pageList(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        retMap.put("success", true);

        return retMap;
    }

    /**
     * 查询患者宝宝是否已结案。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/queryClosedRecord")
    public Map<String, Object> queryClosedRecord(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryClosecase()----arg==" + arg);
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        final String babyId = jsonData.getString("patientId");
        if (StringUtils.isEmpty(babyId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者patientId未传或值为空！"));
        }
        //已登录账户，从session中获取。
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String authorId   = sessionMap.get("authorId").toString();
        final String tenantId   = sessionMap.get("tenantId").toString();
        //查询该病人是否已经结案.
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("userId",  babyId);
        HashMap<String, Object> closeMap = patientSerivce.pageList(paramMap);
        if(null != closeMap ){
            List rows = (List) closeMap.get("rows");
            if(rows.size() > 0){
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "该患者已结案，请不要重复操作！可在【患者管理】->【结案人员列表】中查询已结案人员。"));
            }
        }

        Map<String,Object> retMap   = new HashMap<>();
        retMap.put("success","true");
        return retMap;
    }


    /**
     * 转诊-发起转诊
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/applyReferral")
    public ResultModel<Object> applyReferral(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in savePatientInfo----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonObject = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonObject) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String tenantName = (String) sessionMap.get("tenantName");// 租户名称
        String refTenantId = (String) sessionMap.get("refTenantId");//关联上级医院id
        JSONArray userIds = (JSONArray) jsonObject.get("userIds");
        for (Object jsonData : userIds) {
            buildPatientInfo((JSONObject) jsonData, author, tenantId, tenantName);
        }

        return new ResultModel<Object>("");
    }

    /**
     * 组织病人转诊信息并存入到fuReferralRecord表
     * @param jsonData
     * @param author
     * @param tenantId
     * @param tenantName
     * @throws Exception
     */
    private void buildPatientInfo(JSONObject jsonData, String author, String tenantId, String tenantName) throws Exception {
        String currTime = jsonData.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_USER_REFERRAL_ID);// 操作流水

        // 参数校验后续补充
        String userId = jsonData.getString("userId");
        if(StringUtils.isEmpty(userId)){
            logger.debug("out applyReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        String ptSchemeId = jsonData.getString("ptSchemeId");
        if(StringUtils.isEmpty(ptSchemeId)){
            logger.debug("out applyReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者方案id不能为空");
        }

        Map<String,Object> userMap = new HashMap<String,Object>();
        userMap.put("userId", userId);
        userMap.put("tenantId", tenantId);
        Patient pt = patientSerivce.getPatient(userMap);
        if(pt == null){
            logger.debug("out applyReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
        }
        HashMap<String, Object> pqsMap = new HashMap<>();
        pqsMap.put("id", author);
        Doctor doctor = doctorManagerService.getDoctorById(pqsMap);
        FuReferralRecord fuReferralRecord = new FuReferralRecord();
        fuReferralRecord.setId(updateAccept);
        fuReferralRecord.setUserId(userId);
        fuReferralRecord.setUserName(pt.getUserName());
        fuReferralRecord.setGender(pt.getGender());
        fuReferralRecord.setBirthday(pt.getBirthday());
        fuReferralRecord.setPhoneNo(pt.getPhoneNo());
        fuReferralRecord.setFileNo(pt.getFileNo());
        fuReferralRecord.setUserStatus(Constants.PTUSER_PATIENT_USER_STATUS_WAIT_ACCEPTS);
        fuReferralRecord.setApplyTime(currTime);
        fuReferralRecord.setTenantId(tenantId);
        fuReferralRecord.setSourceHosName(tenantName);
        fuReferralRecord.setConnectPhone(doctor.getPhoneNo());
        fuReferralRecord.setCreateTime(currTime);
        fuReferralRecord.setCreateAuthor(author);
        fuReferralRecord.setUpdateTime(currTime);
        fuReferralRecord.setUpdateAuthor(author);
        fuReferralRecord.setPtSchemeId(ptSchemeId);
        fuReferralRecordService.insert(fuReferralRecord);
        //数据插入到申请记录表去，修改用户状态为等待接诊
        HashMap<String, Object> map = new HashMap<>();
        map.put("updateTime", currTime);
        map.put("userId",userId);
        map.put("userStatus", Constants.PTUSER_PATIENT_USER_STATUS_WAIT_ACCEPTS);
        patientDao.updatePatientInfoById(map);
    }

    /**
     * 转诊--接诊
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/receiveReferral")
    public ResultModel<Object> receiveReferral(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in savePatientInfo----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonObject = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonObject) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String tenantName = (String) sessionMap.get("tenantName");// 租户名称
        String refTenantId = (String) sessionMap.get("refTenantId");//关联上级医院id
        String currTime = jsonObject.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }
        // 参数校验后续补充
        String id = jsonObject.getString("id");
        if(StringUtils.isEmpty(id)){
            logger.debug("out receiveReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，记录ID不能为空");
        }

        String userStatus = jsonObject.getString("userStatus");//前台传入用户状态，3是已接诊 5是拒绝 4转回
        if(StringUtils.isEmpty(userStatus)){
            logger.debug("out receiveReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户状态不能为空");
        }

        String queueId = jsonObject.getString("queueId");
        if(Constants.PTUSER_PATIENT_USER_STATUS_ALREADY_REFERRAL.equals(userStatus) && StringUtils.isEmpty(queueId)){//接收转诊必须要有队列id
            logger.debug("out receiveReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，转入队列不能为空");
        }
        String remark = jsonObject.getString("remark");//拒绝原因
        if(Constants.PTUSER_PATIENT_USER_STATUS_REFUSED.equals(userStatus) && StringUtils.isEmpty(remark)){//拒绝接收转诊必须要有拒绝原因
            logger.debug("out receiveReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，拒绝原因不能为空");
        }
        //更改待转入表用户状态、病人基本信息表状态
        FuReferralRecord fuReferralRecord = fuReferralRecordService.load(id);
        fuReferralRecord.setUserStatus(userStatus);
        if(StringUtils.isNotEmpty(queueId)){
            fuReferralRecord.setQueueId(queueId);
        }
        if(StringUtils.isNotEmpty(remark)){
            fuReferralRecord.setRemark(remark);
        }

        fuReferralRecord.setUpdateAuthor(author);
        fuReferralRecord.setUpdateTime(currTime);
        fuReferralRecordService.update(fuReferralRecord);

        //修改用户状态
        HashMap<String, Object> map = new HashMap<>();
        map.put("updateTime", currTime);
        map.put("userId",fuReferralRecord.getUserId());
        map.put("tenantId",fuReferralRecord.getTenantId());
        map.put("userStatus", userStatus);
        patientDao.updatePatientInfoById(map);

        return new ResultModel<Object>("");
    }

    @ResponseBody
    @RequestMapping("/getFuReferralRecord")
    public Map<String, Object> getFuReferralRecord(@RequestBody String arg,
                                                   HttpServletRequest request) throws Exception {
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String refTenantId = (String) sessionMap.get("refTenantId");//关联上级医院id
        String refTenantName = "";
        if(StringUtils.isNotBlank(refTenantId)){
            Map<String, Object> map = new HashMap<>();
            map.put("id", refTenantId);
            List<Map<String, Object>> maps = fuReferralRecordService.selectTenant(map);
            if(null !=  maps && maps.size() > 0){
                Map<String, Object> o = (Map<String, Object>) maps.get(0);
                refTenantName = (String) o.get("name");
            }
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        String tenantId = jsonData.getString("tenantId");//前台传递为来源医院id，根据医院查询
        String userName = jsonData.getString("userName");
        String userStatus = jsonData.getString("userStatus");
        String phoneNum = jsonData.getString("phoneNum");
        String startTime = jsonData.getString("startTime");
        String endTime = jsonData.getString("endTime");
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (StringUtils.isNotBlank(tenantId)) {
            paramMap.put("tenantId", tenantId);
        }
        if (StringUtils.isNotBlank(userName)) {
            paramMap.put("userName", userName);
        }
        if (StringUtils.isNotBlank(userStatus)) {
            paramMap.put("userStatus", userStatus);
        }
        if (StringUtils.isNotBlank(phoneNum)) {
            paramMap.put("phoneNum", phoneNum);
        }
        if (StringUtils.isNotBlank(startTime)) {
            paramMap.put("startTime", startTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            paramMap.put("endTime", endTime);
        }

        if(StringUtils.isBlank(tenantId) && StringUtils.isNotBlank(refTenantId)){//分中心则查询当前租户的数据
            paramMap.put("tenantId", (String) sessionMap.get("tenantId"));
        }

        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);


        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }
        Map<String, Object> retMap = fuReferralRecordService.pageList(paramMap);
        List<Map<String, Object>> records = (List<Map<String, Object>>) retMap.get("rows");
        if(null != records && records.size() > 0){
            for (Map<String, Object> record : records) {
                String ptSchemeId = (String) record.get("ptSchemeId");
                Map<String, Object> taskMap = new HashMap<String, Object>();
                taskMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
                taskMap.put("ptSchemeId", ptSchemeId);
                taskMap.put("taskType", Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务
                List<PatientTask> taskList = patientTaskDao.select(taskMap);
                String id = taskList.get(0).getId();
                record.put("taskId", id);
                record.put("refTenantName", refTenantName);
                //登记医生联系电话,如果建档信息的联系电话不为空则先取建档联系电话
                HashMap<String, Object> argMap = new HashMap<String, Object>();
                argMap.put("taskId", id);
                List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(argMap);
                PatientContentData doctorPhone = ptTaskConList.stream().filter(s -> s.getQuestionId().equals("jd_lxdh")).collect(Collectors.toList()).get(0);
                if(null != doctorPhone && StringUtils.isNotBlank(doctorPhone.getQuestionAnswer())){
                    record.put("doctorPhone", doctorPhone.getQuestionAnswer());
                }
            }
        }

        //records排序
        List<Map<String,Object>> tempList = records.stream().sorted(Comparator.comparingLong((Map<String, Object> e) -> ((Date) (e.get("updateTime"))).getTime()).reversed()).collect(Collectors.toList());
        retMap.put("rows", tempList);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        retMap.put("success", true);

        return retMap;
    }

    /**
     * 转诊--转回
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/returnReferral")
    public ResultModel<Object> returnReferral(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in savePatientInfo----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonObject = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonObject) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String tenantName = (String) sessionMap.get("tenantName");// 租户名称
        String refTenantId = (String) sessionMap.get("refTenantId");//关联上级医院id
        String currTime = jsonObject.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }
        // 参数校验后续补充
        String referralRecordId = jsonObject.getString("referralRecordId");
        if(StringUtils.isEmpty(referralRecordId)){
            logger.debug("out receiveReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，转诊记录ID不能为空");
        }

        String userStatus = jsonObject.getString("userStatus");//前台传入用户状态，3是已接诊 5是拒绝 4转回
        if(StringUtils.isEmpty(userStatus)){
            logger.debug("out receiveReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，用户状态不能为空");
        }

        //更改待转入表用户状态
        FuReferralRecord fuReferralRecord = fuReferralRecordService.load(referralRecordId);
        fuReferralRecord.setUserStatus(userStatus);
        fuReferralRecord.setUpdateAuthor(author);
        fuReferralRecord.setUpdateTime(currTime);
        fuReferralRecordService.update(fuReferralRecord);

        FuReferralReturnRecord fuReferralReturnRecord = new FuReferralReturnRecord();
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_USER_REFERRAL_ID);// 操作流水
        fuReferralReturnRecord.setId(updateAccept);
        fuReferralReturnRecord.setUserId(fuReferralRecord.getUserId());
        fuReferralReturnRecord.setReferralRecordId(fuReferralRecord.getId());
        fuReferralReturnRecord.setCreateTime(currTime);
        fuReferralReturnRecord.setCreateAuthor(author);
        String diagnosis = jsonObject.getString("diagnosis");
        if(StringUtils.isNotEmpty(diagnosis)){
            fuReferralReturnRecord.setDiagnosis(diagnosis);
        }
        String checkResult = jsonObject.getString("checkResult");
        if(StringUtils.isNotEmpty(checkResult)){
            fuReferralReturnRecord.setCheckResult(checkResult);
        }
        String treatment = jsonObject.getString("treatment");
        if(StringUtils.isNotEmpty(treatment)){
            fuReferralReturnRecord.setTreatment(treatment);
        }
        String rehabilitationAdvice = jsonObject.getString("rehabilitationAdvice");
        if(StringUtils.isNotEmpty(rehabilitationAdvice)){
            fuReferralReturnRecord.setRehabilitationAdvice(rehabilitationAdvice);
        }
        fuReferralReturnRecordService.insert(fuReferralReturnRecord);

        //修改病人基本信息表状态
        HashMap<String, Object> map = new HashMap<>();
        map.put("updateTime", currTime);
        map.put("userId",fuReferralRecord.getUserId());
        map.put("tenantId",fuReferralRecord.getTenantId());
        map.put("userStatus", userStatus);
        patientDao.updatePatientInfoById(map);

        return new ResultModel<Object>("");
    }

    @ResponseBody
    @RequestMapping("/staticFuReferral")
    public ResultModel<Map<String, Object>> staticFuReferral(@RequestBody String arg, HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonObject = null;
        if(null != jsonArg ){
            paramMap.put("year", jsonObject.getString("year"));
            jsonObject = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
            if (null == jsonObject) {
                // 前台必须传data节点，否则报错返回
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
            }
        }
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String refTenantId = (String) sessionMap.get("refTenantId");// 分中心上级编码
        if(StringUtils.isNotBlank(refTenantId)){
            paramMap.put("tenantId", tenantId);
        }
        //总人数
        int total = fuReferralRecordDao.pageListCount(paramMap);
        //本周人数
        int weekCount = fuReferralRecordDao.staticThisWeekCount(paramMap);
        //年 月度人数
        List<Map<String, Object>> maps = fuReferralRecordDao.staticYearAndMonthCount(paramMap);
        //转诊 状态人数占比
        List<Map<String, Object>> maps1 = fuReferralRecordDao.staticUserStatusPercent(paramMap);
        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("总人数",total);
        retMap.put("本周人数",weekCount);
        retMap.put("年/月度人数",maps);
        retMap.put("各状态人数占比",maps1);
        return new ResultModel<Map<String, Object>>(retMap);
    }

    @ResponseBody
    @RequestMapping("/queryAutenant")
    public ResultModel<List<Map<String, Object>>> queryAutenant(HttpServletRequest request) throws Exception {
        List<Map<String, Object>> maps = fuReferralRecordService.selectTenant(new HashMap<String, Object>());
        return new ResultModel<>(maps);
    }

    /**
     * 转诊--转回记录
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/getReturnReferral")
    public ResultModel<Object> getReturnReferral(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in savePatientInfo----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonObject = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonObject) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String userId = jsonObject.getString("userId");
        if(StringUtils.isEmpty(userId)){
            logger.debug("out receiveReferral----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，病人ID不能为空");
        }

        HashMap<String, Object> paramMapIn = new HashMap<>();
        paramMapIn.put("userId", userId);
        List<Map<String, Object>> returnReferral = fuReferralRecordDao.getReturnReferral(paramMapIn);
        return new ResultModel<Object>(returnReferral);
    }

    /**
     * 患者列表
     * @param reqDTO
     * @param request
     * @return
     */
    @PostMapping("/patientListPage")
    public ResultModel patientListPage(@RequestBody PatientPageReqDTO reqDTO, HttpServletRequest request) throws Exception {
        //59.PC端--患者列表：按建档时间倒序排列。(2022-07-26)
        //已按照建档时间倒序排列。
        Map<String,Object> map = patientSerivce.patientListPage(reqDTO,request);
        return new ResultModel(map);
    }

    /**
     * 医院列表 医院下拉选择列表
     * @param request
     * @return
     */
    @GetMapping("/hospitalList")
    public ResultModel hospitalList(HttpServletRequest request) {
        List<String> hospitalList= patientSerivce.hospitalList(request);
        return new ResultModel(hospitalList);
    }

    /**
     * 修改患者状态
     * @param reqDTO
     * @param request
     * @return
     */
    @PostMapping("/updatePatientStatus")
    public ResultModel updatePatientStatus(@RequestBody PatientUpdateStatusReqDTO reqDTO, HttpServletRequest request) throws Exception {
        patientSerivce.updatePatientStatus(reqDTO,request);
        return new ResultModel("更新成功");
    }

}
